package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.IotClientConfig;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.apache.commons.compress.archivers.sevenz.CLI;
import org.apache.commons.math3.analysis.function.Add;
import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.stream.Collectors;

/**
 * 设备详细Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-23
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备详细
     * 
     * @param id 设备详细主键
     * @return 设备详细
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备详细列表
     * 
     * @param device 设备详细
     * @return 设备详细
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备详细
     * 
     * @param device 设备详细
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备详细
     * 
     * @param device 设备详细
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备详细
     * 
     * @param ids 需要删除的设备详细主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备详细信息
     * 
     * @param id 设备详细主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品信息
     */
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IoTDAClient ioTDAClient;
    @Override
    public void syncProductList() {
        ListProductsResponse listProductsResponse = ioTDAClient.listProducts(new ListProductsRequest());
        List<ProductSummary> products = listProductsResponse.getProducts();
        String jsonStr = JSONUtil.toJsonStr(products);
        redisTemplate.opsForValue().set(Constants.PRODUCT_LIST_KEY,jsonStr);
    }

    /**
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String s = redisTemplate.opsForValue().get(Constants.PRODUCT_LIST_KEY);
        if (StrUtil.isBlank(s)){
            return Collections.emptyList();
        }
        List<ProductSummary> list = JSONUtil.toList(s, ProductSummary.class);
        List<ProductVo> collect = list.stream().map(l -> ProductVo.builder().productName(l.getName()).productKey(l.getProductId()).build())
                .collect(Collectors.toList());
        return collect;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(DeviceDto dto) {
        Long count = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (count>0){
            throw new BaseException("设备名称重复");
        }
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        Long count1 = this.lambdaQuery().eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getProductKey, dto.getProductKey()).count();
        if (count1>0){
            throw new BaseException("请勿在相同位置绑定同类产品");
        }
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setProductId(dto.getProductKey());
        addDevice.setDeviceName(dto.getDeviceName());
        addDevice.setDescription(dto.getDeviceDescription());
        addDevice.setNodeId(nodeId);
        AuthInfo authInfo = new AuthInfo();
        String secret = IdUtil.fastSimpleUUID();
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        request.setBody(addDevice);
        AddDeviceResponse response = null;
        try {
            response = ioTDAClient.addDevice(request);
            if (response.getHttpStatusCode()!= HttpStatus.HTTP_CREATED){
                throw new BaseException("注册失败");
            }


        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("注册失败");
        }
        String iotid = response.getDeviceId();
        Device bean = BeanUtil.toBean(dto, Device.class);
        bean.setIotId(iotid);
        bean.setNodeId(nodeId);
        bean.setSecret(secret);
        String productName = response.getProductName();
        bean.setProductName(productName);
        bean.setHaveEntranceGuard(dto.getNickname().contains("门禁")?1:0);
        this.save(bean);
    }
    @Autowired
    private HuaWeiIotConfigProperties properties;
    @Autowired
    private ISysUserService userService;
    /**
     * 查询设备详情
     *
     * @param iotId
     * @param productKey
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId, String productKey) {
        Device one = this.lambdaQuery().eq(Device::getIotId, iotId).eq(Device::getProductKey, productKey)
                .one();
        if (one==null){
            throw new BaseException("表中设备不存在");
        }
        DeviceDetailVo bean = BeanUtil.toBean(one, DeviceDetailVo.class);
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
         showDeviceRequest.withDeviceId(iotId);
        try {
            ShowDeviceResponse response = ioTDAClient.showDevice(showDeviceRequest);
            if (response.getHttpStatusCode()!=200){
                throw new BaseException("云端设备不存在");
            }
            bean.setRegion(properties.getRegionId());
            bean.setDeviceStatus(response.getStatus());
            bean.setFirmwareVersion(response.getFwVersion());
            bean.setGmtCreate(one.getCreateTime());
            bean.setCreator(one.getCreateBy());
            bean.setDeviceSecret(one.getSecret());
            if (response.getActiveTime()!=null){
                LocalDateTime localDateTime = OffsetDateTime.parse(response.getActiveTime())
                        .atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
                bean.setGmtActive(localDateTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("云端设备不存在");
        }

        return bean;
    }

    /**
     * 获取产品物模型数据
     *
     * @param productKey
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        try {
            ShowProductResponse response = ioTDAClient.showProduct(request);
            if (response.getHttpStatusCode()!=HttpStatus.HTTP_OK){
                throw new BaseException("云端获取产品失败");
            }
            List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
            JSONObject entries = JSONUtil.parseObj(serviceCapabilities.get(0));
            return entries;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("云端获取产品失败");
        }

    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param deviceName
     * @param productKey
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName, String productKey) {
    //获取nodeid
        Device one = this.lambdaQuery().eq(Device::getDeviceName, deviceName)
                .eq(Device::getProductKey, productKey).select(Device::getIotId)
                .one();
        if (ObjectUtil.isEmpty(one)){
            throw new BaseException("表中不存在此设备");
        }
        String iotId = one.getIotId();
        //iot平台查询影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        try {
            ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
            if (response.getHttpStatusCode()!=HttpStatus.HTTP_OK){
                throw new BaseException("云端获取设备数据失败");
            }
            if (response.getShadow()==null){
                throw new BaseException("云端无设备数据");
            }
            DeviceShadowProperties reported = response.getShadow().get(0).getReported();
            String eventTime = reported.getEventTime();
            LocalDateTime time = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX")).toLocalDateTime();
            ArrayList<Map> properties = new ArrayList<>();
            JSONObject entries = JSONUtil.parseObj(reported.getProperties());
            entries.forEach((k,v)->{
                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("identifier",k);
                map1.put("value",v);
                map1.put("time",time);
                properties.add(map1);
            });
            HashMap<String, Object> list = new HashMap<>();
            list.put("propertyStatusInfo",properties);
            HashMap<String,Object> data = new HashMap<>();
            data.put("list",list);
            return data;

        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("云端中不存在此设备");
        }


        //截取reported和eventtime

        //遍历properties存入map再装如集合propertinfo再装入map返回

    }

    /**
     * 删除设备
     *
     * @param productKey
     * @param iotId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(String productKey, String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            ioTDAClient.deleteDevice(request);
            this.lambdaUpdate().eq(Device::getIotId,iotId).eq(Device::getProductKey,productKey)
                    .remove();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("删除失败");
        }

    }
}
